
#include<stdio.h>
#include<unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>

int ticket = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
//gcc -o mutex TestMutex.cc -std=c++11 -lpthread 使用锁时，需要软链接pthread库
void* route (void *arg){
    //任务进程返回nullptr

    char *id = (char*) arg;
    while(1){
        pthread_mutex_lock(&lock);
        //创建锁，进行排队
        if(ticket > 0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", id, ticket);
            ticket--;
            //解锁
            pthread_mutex_unlock(&lock);
        }
        else{
            pthread_mutex_unlock(&lock);
            break;
        }
    }
    return nullptr;
}


int main(void){
    pthread_t t1, t2, t3, t4;
    //创建线程
    pthread_create(&t1, NULL, route, (void *)"thread 1");
    pthread_create(&t2, NULL, route, (void *)"thread 2");
    pthread_create(&t3, NULL, route, (void *)"thread 3");
    pthread_create(&t4, NULL, route, (void *)"thread 4");
    
    //等待线程
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    return 0;
}
